package com.lzq.mq.nameserver.event.handler;

import com.alibaba.fastjson2.JSON;
import com.lzq.mq.common.coder.TcpMsg;
import com.lzq.mq.common.enums.NameServerEventCode;
import com.lzq.mq.common.event.model.Event;
import com.lzq.mq.nameserver.common.CommonCache;
import com.lzq.mq.common.event.EventBus;
import com.lzq.mq.nameserver.event.model.*;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * 主从模式下的数据复制handler
 */
@Slf4j
@ChannelHandler.Sharable
public class SlaveReplicationServerHandler extends SimpleChannelInboundHandler<TcpMsg> {

    private EventBus eventBus;

    public SlaveReplicationServerHandler(EventBus eventBus) {
        this.eventBus = eventBus;
    }

    // 1.网络请求的接受
    // 2.事件发不起的实现 事件总线->event
    // 3.事件处理器的实现
    // 4.数据存储
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TcpMsg tcpMsg) throws Exception {

        int code = tcpMsg.getCode();
        byte[] body = tcpMsg.getBody();
        Event event = null;
        if (NameServerEventCode.MASTER_REPLICATION_MSG.getCode() == code) {
            event = JSON.parseObject(body, ReplicationMsgEvent.class);
        } else if(NameServerEventCode.MASTER_START_REPLICATION_ACK.getCode() == code) {
            CommonCache.getIsConnectedReplicationServer().set(true);
            log.info("成功连接到同步节点!");
            return;
        }
        if (event == null) {
            log.error("event is null:{}", tcpMsg);
        }
        event.setChannelHandlerContext(channelHandlerContext);
        eventBus.publish(event);
    }

    /**
     * 异常处理
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
    }

    /**
     * 断开连接处理
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
    }
}
